var rest = require('restler');
var urlencode = require("urlencode");
var fs = require('fs');

sprintf = require('sprintf').sprintf;

module.exports = function(app) {
	var doctor_Db = require('../model/doctor_db');

	//json = {
	//    "name":"",
	//    "id":"",
	//    "type":"",   travelling, hotel, 
	//    "time":"",
	//    "price":"",
	//    "start_time":'',
	//    "end_time":'',
	//    "start_city":"",
	//    "end_city":"",
	//    "showurl":"",
	//    "jumpurl":"",
	//    "content":"",
	//}
	
	app.get('/doctor/add', function (req, res) {
		console.log(req.query.json);
		var data = JSON.parse(req.query.json);

		//trans_url(data);

		//console.log(data);

		doctor_Db.add(data, function() {
			res.send("add finish");
		});
	});

	//json = {
	//	"start_city":"",
	//	"end_city":"",
	//	"time":"",
	//}

	///doctor/search?json={"test":{"$gt":3},"limit":20,"skip":0}
	app.get('/doctor/search', function (req, res) {
		var data = JSON.parse(req.query.json);
		doctor_Db.search(data, function(DbRes) {
			var Strres=JSON.stringify(DbRes);
			console.log("finish search");
			res.send(Strres);
		});
	});

	//json = {
	//   "id":"",
	//}

	app.get('/doctor/del', function (req, res) {
		var data = JSON.parse(req.query.json);
		doctor_Db.del(data, function(DbRes) {
			var Strres=JSON.stringify(DbRes);
			console.log("finish delete");
			res.send(Strres);
		});
	});

	app.post('/doctor/put', function (req, res) {
		console.log("doctor put");

		/*
		console.log(req.files);
		var tmp_path = req.files.thumbnail.path;
		var target_path = './public/images/' + req.files.thumbnail.name;
		fs.rename(tmp_path, target_path, function(err) {
			if (err) throw err;
			fs.unlink(tmp_path, function() {
				if (err) throw err;
				res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
			});
		});
		*/
		var fstream;
		req.pipe(req.busboy);
		req.busboy.on('file', function (fieldname, file, filename) {
			console.log("Uploading: " + filename); 
			fstream = fs.createWriteStream(__dirname + '/updates/' + filename);
			file.pipe(fstream);
			fstream.on('close', function () {
				res.redirect('back');
			});
		});
	});
};
